<template>
    <div>
        <global-tables
            :total="total"
            :list="list"
            :loading="loading"
            :columns="columns"
            :current="formValidate.pageindex"
            @changePage="handleChangePage"
            @handleAllSelect="handleAllSelect"
            @handleChangeSwitch="handleChangeSwitch"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                            <Icon type="md-add" size="18"/>新建
                        </Button>
                        <Button v-if="isDeleteBtn" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                            <Icon class="btn btn-auto-m" type="md-trash" size="18"/>删除
                        </Button>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input
                                type="text"
                                style="width: 170px"
                                class="style-input"
                                @keyup.enter="handleSearch"
                                v-model="search.keyword"
                                placeholder="请输入用户名 / 公司名称 "
                            >
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" class="search-btn" @click="handleSearch">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <div>
            <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle">
                <div v-if="isModal">
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
                        <Row>
                            <i-col :lg="{ span: 15}" v-if="ModalTitle == '新建用户'">
                                <FormItem label="用户名" prop="Account">
                                    <i-input v-model="formValidate.Account" placeholder="请输入用户名 / 英文 /  最长10字"></i-input>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="真实姓名" prop="RealName">
                                    <i-input v-model="formValidate.RealName" placeholder="请输入真实姓名"></i-input>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="手机" prop="Mobile">
                                    <i-input v-model="formValidate.Mobile" placeholder="请输入用户名 / 英文 /  最长10字"></i-input>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="角色" prop="RoleID" class="form-item-width">
                                    <Select :label-in-value="true" v-model="formValidate.RoleID" style="width:200px">
                                        <Option v-for="(item,index) in formValidate.role" :value="item.value +''" :key="index">{{item.name}}</Option>
                                    </Select>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="邮箱" prop="Email">
                                    <i-input v-model="formValidate.Email" placeholder="请输入用户名 / 英文 /  最长10字"></i-input>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="性别">
                                    <RadioGroup v-model="formValidate.Gender">
                                        <Radio label="true">男</Radio>
                                        <Radio label="false">女</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="状态" prop="AllowLogin">
                                    <RadioGroup v-model="formValidate.AllowLogin">
                                        <Radio label="true">启用</Radio>
                                        <Radio label="false">停用</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 20}">
                                <FormItem label="备注">
                                    <i-input type="textarea" v-model="formValidate.Remark" placeholder="请输入备注"></i-input>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div slot="footer">
                    <Button size="large" @click="handleClose">取消</Button>
                    <Button type="primary" size="large" @click="handleSubmit('formValidate')">确定</Button>
                </div>
            </Modal>
        </div>
    </div>
</template>

<script>
/**
 * 用户列表
 */
import { cyclicRouting, getdate } from '@/util';
import { getModulePermission } from '@/api/user';
import { getTablesList, getRole, addTablesItem, getItemInfo, setEnable, setDisabled, dleTablesItem } from './service';
import GlobalTables from '@/components/GlobalTables';
export default {
    name: 'SystemUser',
    components: {
        GlobalTables
    },
    data() {
        return {
            moduleid: '',
            isModal: false,
            loading: true,
            total: 0,
            role: '',
            isTime: true,
            ModalTitle: '新建用户',
            isAddBtn: false,
            isDeleteBtn: false,
            isEdit: false,
            allSelectArr: null,
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10
            },
            isSwitch: false,
            type: 'add',
            itemId: null,
            formValidate: this.initFormValidate(),
            ruleValidate: this.initRuleValidate(),
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '用户名',
                    key: 'Account'
                },
                {
                    title: '真实姓名',
                    key: 'RealName',
                    width: '100px'
                },
                {
                    title: '性别',
                    width: 80,
                    render: (h, params) => {
                        const { Gender } = params.row;
                        if (Gender) {
                            return h('div', [h('span', '男')]);
                        } else {
                            return h('div', [h('span', '女')]);
                        }
                    }
                },
                {
                    title: '手机号',
                    key: 'Mobile',
                    width: 115
                },
                {
                    title: '邮箱',
                    key: 'Email',
                    width: '150px'
                },
                {
                    title: '角色',
                    key: 'RoleName',
                    width: 140
                },
                {
                    title: '允许登录',
                    width: 100,
                    render: (h, params) => {
                        const { AllowLogin } = params.row;
                        if (AllowLogin) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'success',
                                        text: '是'
                                    }
                                })
                            ]);
                        } else {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '否'
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: '创建时间',
                    key: 'CreateTime',
                    width: 140,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'span',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    }
                                },
                                getdate(new Date(params.row.CreateTime).getTime())
                            )
                        ]);
                    }
                },
                {
                    title: '操作',
                    width: 120,
                    align: 'center',
                    render: (h, params) => {
                        const { isEdit, isSwitch } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '编辑'
                                ),
                            isSwitch &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: params.row.AllowLogin ? 'rgb(252, 134, 117)' : 'rgb(101, 206, 167)',
                                            border: 'none'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleChangeSwitch(params.row, params.row.AllowLogin ? '停用' : '启用');
                                            }
                                        }
                                    },
                                    params.row.AllowLogin ? '停用' : '启用'
                                )
                        ]);
                    }
                }
            ],
            list: []
        };
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        /* 如果用户权限有新建 */
                        this.setAddButton();
                    } else if (res.data[item].name == 'delete') {
                        this.isDeleteBtn = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    } else if (res.data[item].name == 'onoff') {
                        this.isSwitch = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    },
    methods: {
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 表格清空 */
        handleEmpty() {
            this.search.keyword = '';
            this.getTablesListData();
        },
        /* 新建按钮显示 */
        setAddButton() {
            this.isAddBtn = true;
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        },
        /* 对话框提交 */
        handleSubmit(name) {
            const { formValidate, itemId } = this;
            this.$refs[name].validate(valid => {
                if (valid) {
                    let data = {
                        ID: itemId,
                        Account: formValidate.Account,
                        RealName: formValidate.RealName,
                        Mobile: formValidate.Mobile,
                        Email: formValidate.Email,
                        RoleID: formValidate.RoleID,
                        AllowLogin: eval(formValidate.AllowLogin.toLowerCase()),
                        Gender: eval(formValidate.Gender.toLowerCase()),
                        Remark: formValidate.Remark,
                        UID: JSON.parse(sessionStorage.getItem('user')).uid
                    };
                    addTablesItem(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.handleClose();
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 开关点击 */
        handleChangeSwitch(item, title) {
            this.$Modal.confirm({
                title: `你确定要${title}吗`,
                onOk: () => {
                    const { ID } = item;
                    const uid = JSON.parse(sessionStorage.getItem('user')).uid;
                    if (!item.AllowLogin) {
                        setEnable({
                            ID,
                            uid
                        }).then(res => {
                            this.$Message.success(res.message);
                            this.getTablesListData();
                        });
                    } else {
                        setDisabled({
                            ID,
                            uid
                        }).then(res => {
                            this.$Message.success(res.message);
                            this.getTablesListData();
                        });
                    }
                },
                onCancel: () => {
                    this.$Message.info('取消成功');
                }
            });
        },
        /* 对话框操作点击 */
        handleBtnClick(item, type) {
            this.initFormValidate();
            if (type == 'edit' || type == 'add') {
                this.itemId = 0;
                this.isModal = true;
                getRole({
                    companyId: JSON.parse(sessionStorage.getItem('user')).comid
                }).then(res => {
                    this.formValidate.role = res.data;
                });
                if (type == 'edit') {
                    this.type = 'edit';
                    this.itemId = item.ID;
                    this.ModalTitle = '修改用户';
                    // 获取一条的id;
                    getItemInfo({
                        id: item.ID
                    }).then(res => {
                        const { AllowLogin } = res.data;
                        if (AllowLogin) {
                            this.isTime = true;
                        } else {
                            this.isTime = false;
                        }
                        // 赋值给表单;
                        this.formValidate = {
                            ...this.formValidate,
                            Account: res.data.Account,
                            RealName: res.data.RealName,
                            Mobile: res.data.Mobile,
                            Email: res.data.Email,
                            AllowLogin: res.data.AllowLogin ? 'true' : 'false',
                            Gender: res.data.Gender ? 'true' : 'false',
                            RoleID: res.data.RoleID + '',
                            Remark: res.data.Remark
                        };
                    });
                } else {
                    this.ModalTitle = '新建用户';
                    this.isTime = true;
                    this.formValidate = this.initFormValidate();
                }
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            dleTablesItem({
                                ids: this.allSelectArr,
                                UID: JSON.parse(sessionStorage.getItem('user')).uid
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请先选择需要操作的记录');
                }
            }
        },
        /* 表单数据 */
        initFormValidate() {
            return {
                Account: '',
                RealName: '',
                Mobile: '',
                Email: '',
                AllowLogin: 'true',
                Gender: 'true',
                companyId: '',
                role: [],
                roleText: ''
            };
        },
        /* 表单校验 */
        initRuleValidate() {
            return {
                Account: [
                    {
                        required: true,
                        message: '请输入用户名 / 英文 / 最长10字',
                        trigger: 'change',
                        pattern: '^[a-zA-Z]+$'
                    }
                ],
                Mobile: [
                    {
                        required: true,
                        message: '请输入正确手机号码',
                        pattern: /^[1][3,4,5,7,8][0-9]{9}$/
                    }
                ],
                RoleID: [{ required: true, message: '请选择角色', trigger: 'change' }],
                RealName: [
                    {
                        required: true,
                        message: '请输入真实姓名',
                        trigger: 'change'
                    }
                ],
                role: [{ required: true, message: '请选择角色', trigger: 'change' }]
            };
        }
    }
};
</script>

<style lang="less" scoped>
.form-item-width {
    width: 300px;
}
.btn-wrap {
    margin: 0 15px;
}
.dle-btn {
    margin: 0 10px;
}
.search-con {
    padding: 10px 0;
    .search {
        &-col {
            display: inline-block;
            width: 200px;
        }
        &-input {
            display: inline-block;
            width: 200px;
            margin-left: 2px;
        }
        &-btn {
            margin-left: 2px;
        }
    }
}
</style>


